package bot;

import com.google.appengine.api.xmpp.JID;

import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable
public class ChatUser {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private String email;

    @Persistent
    private String jid;

    @Persistent
    private String name;		// name part of email address
    
    @Persistent
    private String nick;

    @Persistent
    private Date lastSeen;
    
    @Persistent
    private Date lastActive;
    
    @Persistent
    private boolean online;

    public ChatUser(JID jid, String nickName, boolean online, Date lastSeen) {
        this.jid = jid.toString();
        this.email = ChatUser.jid2email(jid);
        this.name = email.substring(0, email.indexOf("@"));
        if (nickName != null && !nickName.equals("")) {
        	this.nick = nickName;
        }
        else {
        	this.nick = name;
        }
        this.online = online;
        this.lastSeen = lastSeen;
        this.lastActive = lastSeen;
    }

    // Accessors for the fields. JDO doesn't use these, but your application does.

    public JID getJid() {
        return new JID(email);
    } 

    public String getEmail() {
        return email;
    } 

    public String getNick() {
        return nick;
    } 

    public Date getLastSeen() {
        return lastSeen;
    }
    
    public String getLastSeenFormatted() {
    	return date2format(getLastSeen());
	}
    
    public Date getLastActive() {
        return lastActive;
    }
    
    public String getLastActiveFormatted() {
    	return date2format(getLastActive());
	}
    
    private String date2format(Date date) {
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
		sdf.setTimeZone(java.util.TimeZone.getTimeZone("Europe/Amsterdam"));
		return sdf.format(date);
    }
    
    public boolean isOnline() {
    	return online;
    }

    public void setOnline(boolean online) {
    	this.online = online;
    }

    public void setLastSeen(Date date) {
    	this.lastSeen = date;
    }
    
    public void setLastActive(Date date) {
    	this.lastActive = this.lastSeen = date;
    }
    
    public void setNick(String nick) {
    	this.nick = nick;
    }
    
    public static String jid2email(JID jid) {
    	return ChatUser.jid2email(jid.toString());
    }
    
	public static String jid2email(String jid) {
		String email = jid;
		if (email.startsWith("<JID: ")) {
			email = email.substring(6);
		}
		if (email.contains("/")) {
			email = email.substring(0, email.indexOf("/"));
		}
		if (email.contains(">")) {
			email = email.substring(0, email.indexOf(">"));
		}
		return email;
	}
		


}